using AutoMapper;
using BackData;
using Domain.BOM;
using Domain.DTOs.BOMs;
using Infratructure;
using MediatR;
using Team.API.Applocation.Command.BOM;

namespace Team.API.Applocation.Hanldler.BOM
{
    /// <summary>
    /// 获取BOM物料列表处理器（排除成品）
    /// </summary>
    public class GetBOMListHandler : IRequestHandler<GetBOMListCommand, APIPaging<BOMListDTO>>
    {
        private readonly IRepository<Bomtable> bomRepository;
        private readonly IMapper mapper;
        private readonly ILogger<GetBOMListHandler> logger;

        public GetBOMListHandler(
            IRepository<Bomtable> bomRepository,
            IMapper mapper,
            ILogger<GetBOMListHandler> logger)
        {
            this.bomRepository = bomRepository;
            this.mapper = mapper;
            this.logger = logger;
        }

        /// <summary>
        /// 获取BOM物料列表（排除成品）
        /// </summary>
        /// <param name="request">查询命令</param>
        /// <param name="cancellationToken">取消令牌</param>
        /// <returns>分页结果</returns>
        public Task<APIPaging<BOMListDTO>> Handle(GetBOMListCommand request, CancellationToken cancellationToken)
        {
            var result = new APIPaging<BOMListDTO>();

            try
            {
                // 基础查询：排除成品和已删除的记录
                var query = bomRepository.GetAll()
                    .Where(x => x.IsDel == false);

                // 物料名称筛选
                if (!string.IsNullOrWhiteSpace(request.GoodsName))
                {
                    query = query.Where(x => x.Goodsname != null && x.Goodsname.Contains(request.GoodsName));
                }

                // 物品编号筛选
                if (!string.IsNullOrWhiteSpace(request.Itemcode))
                {
                    query = query.Where(x => x.Itemcode != null && x.Itemcode.Contains(request.Itemcode));
                }

                // 分类筛选（如果指定了分类，进一步筛选）
                if (!string.IsNullOrWhiteSpace(request.Category))
                {
                    query = query.Where(x => x.Category == request.Category);
                }

                // 父级Id筛选，用于限定某个成品下的配件
                if (!string.IsNullOrWhiteSpace(request.Parentid))
                {
                    query = query.Where(x => x.Parentid == request.Parentid);
                }

                // 获取总数
                var totalCount = query.Count();

                if (totalCount > 0)
                {
                    // 分页查询
                    var list = query
                        .OrderByDescending(x => x.Id)
                        .Skip((request.Pageindex - 1) * request.Pagesize)
                        .Take(request.Pagesize)
                        .ToList();

                    // 映射到DTO
                    var dtoList = mapper.Map<List<BOMListDTO>>(list);

                    result.Totalcount = totalCount;
                    result.Code = StateCode.OK;
                    result.Message = "BOM物料列表获取成功";
                    result.ListResult = dtoList;
                }
                else
                {
                    result.Totalcount = 0;
                    result.Code = StateCode.OK;
                    result.Message = "未找到符合条件的物料";
                    result.ListResult = new List<BOMListDTO>();
                }
            }
            catch (Exception ex)
            {
                logger.LogError(ex, "获取BOM物料列表时发生错误");
                result.Code = StateCode.Fail;
                result.Message = "BOM物料列表获取失败：" + ex.Message;
                result.ListResult = new List<BOMListDTO>();
            }

            return Task.FromResult(result);
        }
    }
}

